package belette;

import graphics.Sprite;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.Vector;

import surface.PolylineObject;
import utils.Vector2d;
import bots.IBot;



public class HeartBelette implements IBelette {
	private BeletteManager myMan;
	
	private IBot firedBy;
	private Vector2d coords, velocity;
	private float angle;
	private static final float power = 2F;
	private static final float radius = 7F;
	private static final Sprite sprite = new Sprite("belette.png", new Vector2d(7.5F, 7F));
	
	public HeartBelette(BeletteManager myMan) {
		this.myMan = myMan;
		
		this.firedBy = null;
		this.coords = new Vector2d();
		this.velocity = new Vector2d();
		this.angle = 0F;
	}
	
	public HeartBelette(BeletteManager myMan, IBot firedBy, Vector2d startCoords, Vector2d velocity) {
		this.myMan = myMan;
		
		this.firedBy = firedBy;
		this.coords = startCoords;
		this.velocity = velocity;
		this.angle = 0F;
	}

	public void computeNextFrame() {
		Vector2d nextCoords = new Vector2d();
		
		coords.setSum(coords, velocity);
		angle -= 60F;
		
		nextCoords.setSum(coords, velocity);
		
		if(!myMan.surface.isInSurface(coords, (int)radius)) {
			myMan.planForDeletion(this);
		}
		
		Vector<ArrayList<IBot>> allBots = myMan.botman.getAllBots();
		for(int i = 0; i < allBots.size(); ++i) {
			if(i != firedBy.getTeam()) {
				for(IBot bot : allBots.get(i)) {
					if(bot.getCoords().distance(coords) < radius + bot.botRadius()) {
						hitBot(bot);
						break;
					}
				}
			}
		}
		
		for(PolylineObject obj : myMan.surface.getObjects()) {
			if(obj.intersectsWith(coords, nextCoords)) {
				hitWall(new Vector2d());
				break;
			}
		}
	}

	public void draw(Graphics g) {
		Graphics2D g2d = (Graphics2D)g;
		AffineTransform tmpTransfo = AffineTransform.getTranslateInstance(coords.x - sprite.centerAnchor.x, coords.y - sprite.centerAnchor.y);
		tmpTransfo.rotate(angle, sprite.centerAnchor.x, sprite.centerAnchor.y);
		
		g2d.drawRenderedImage(sprite.image, tmpTransfo);
	}
	
	public void drawDebug(Graphics g) {
		g.setColor(Color.BLUE);
		g.fillRect((int)coords.x - 2, (int)coords.y - 2, 4, 4);
		g.drawOval((int)coords.x - (int)radius, (int)coords.y - (int)radius, (int)radius * 2, (int)radius * 2);
	}

	public IBot firedBy() {
		return firedBy;
	}

	public Vector2d getCoords() {
		return coords;
	}

	public float getPower() {
		return power;
	}

	public float getRadius() {
		return radius;
	}

	public Vector2d getVelocity() {
		return velocity;
	}

	public void hitBot(IBot bot) {
		// TODO Générer une action sur le Bot qui lui fait perdre des points de vie (ou plutôt gagner de l'amûûûûr).
		bot.hitBy(this);
		myMan.planForDeletion(this);
	}

	public void hitWall(Vector2d impactCoords) {
		// TODO Déclencher une explosion ou juste un éclat de belette.
		myMan.planForDeletion(this);
	}

}
